package com.czkt.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.czkt.config.MyShiroRealm;
import com.czkt.entity.SysRole;
import com.czkt.entity.SysUser;
import com.czkt.entity.vo.UserRole;
import com.czkt.service.ISysRoleRightService;
import com.czkt.service.ISysRoleService;
import com.czkt.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2024-06-18
 */
@Controller
public class SysUserController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysRoleRightService sysRoleRightService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/login")
    public String login() {
        return "/login";
    }

    @RequestMapping("/doLogin")
    public String doLogin(String usrName, String usrPassword,
                          @RequestParam(value = "likeMe", defaultValue = "false") Boolean likeMe,
                          HttpSession session, Model model) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(usrName, usrPassword);
        String errStr = stringRedisTemplate.opsForValue().get(usrName + "errorCount:");
        System.out.println(errStr);
        Integer errCount =errStr!=null? Integer.parseInt(errStr):1;
        if (errCount > 5) {
            model.addAttribute("message", "密码错误次数过多，请24小时后再试");
            return "login";
        }
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            UserRole userRole = (UserRole) SecurityUtils.getSubject().getPrincipal();
            userRole.setSysRights(sysRoleRightService.roleRight(userRole.getRoleId()));
            session.setAttribute("loginUser", userRole);
        } catch (UnknownAccountException e) {
            model.addAttribute("message", "账号不存在!");
            return "/login";
        } catch (LockedAccountException e) {
            model.addAttribute("message", "账号被禁用!");
            return "/login";
        } catch (AuthenticationException e) {
            stringRedisTemplate.opsForValue().increment(usrName + "errorCount:",1);
            stringRedisTemplate.expire(usrName + "errorCount:",24, TimeUnit.HOURS);
            model.addAttribute("message", "账号或密码错误");
            return "/login";
        }
        return "/main";
    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "/login";
    }

    @RequestMapping("/user/list")
    public String userList(@RequestParam(value = "usrName",defaultValue = "") String usrName,
                           @RequestParam(value = "roleId",defaultValue = "") Long roleId,
                           @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                           @RequestParam(defaultValue = "3") Integer pageSize, Model model) {
        List<SysRole> role = roleService.list();
        IPage<UserRole> page = userService.selectUserAndRole(usrName, roleId, pageIndex, pageSize);
        model.addAttribute("roles", role);
        model.addAttribute("roleId", roleId);
        model.addAttribute("usrName", usrName);
        model.addAttribute("userPager", page);
        return "/user/list";
    }

    @RequestMapping("/user/edit")
    public String update(String usrId, Model model) {
        List<SysRole> role = roleService.list();
        UserRole userRole = userService.selectUsrId(usrId);
        model.addAttribute("user", userRole);
        model.addAttribute("roles", role);
        return "/user/edit";
    }

    @RequestMapping("/user/save")
    public String toUpdate(SysUser sysUser,HttpSession session) {
        sysUser.setUsrPassword(new SimpleHash("Md5", sysUser.getUsrPassword(), ByteSource.Util.bytes("czkt"), 2).toString());
        userService.toUpdateUser(sysUser);
        UserRole userRole = (UserRole) session.getAttribute("loginUser");
        if(userRole.getUsrName().equals(sysUser.getUsrName())){
            SecurityUtils.getSubject().logout();
            return "/login";
        }
        return "redirect:/user/list";
    }

    @RequestMapping("/crm/user/del/{usrId}")
    @ResponseBody
    public Object deleteSysUser(@PathVariable("usrId") String usrId) {
        userService.deleteByUsrId(usrId);
        Map<String, Object> map = new HashMap<>();
        map.put("delResult", "true");
        return map;
    }

    @RequestMapping("/user/add")
    public String insertUser(Model model) {
        List<SysRole> role = roleService.list();
        model.addAttribute("roles", role);
        return "/user/add";
    }

    @RequestMapping("/user/insert")
    public String toInsertUser(SysUser sysUser) {
        sysUser.setUsrPassword(new SimpleHash("Md5", sysUser.getUsrPassword(), ByteSource.Util.bytes("czkt"), 2).toString());
        userService.toInsertUser(sysUser);
        return "redirect:/user/list";
    }
}
